package com.geek.service.impl;


import com.geek.bean.PageData;
import com.geek.bean.PageParameter;
import com.geek.bean.data.GoodsDetailData;

import com.geek.service.*;
import com.github.pagehelper.PageHelper;
import com.geek.bean.data.CategoryListData;
import com.geek.bean.vo.CategoryVo;
import com.geek.mapper.*;
import com.geek.model.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;
    @Autowired
    MarketFootprintMapper footprintMapper;


    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;
    @Autowired
    CommentService commentService;

    @Autowired
    IssueService issueService;

    @Autowired
    CollectService collectService;
    @Autowired
    SystemService systemService;
    


    @Override
    public long count() {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false);
        long count = goodsMapper.countByExample(example);
        return count;
    }




    @Override
    public List floorGoodsList(int categoryLimit, int categoryGoodsLimit) {
        List<MarketCategory> categoryList = categoryService.list("L1", 1, categoryLimit);
        List<Object> list = categoryList.stream().map(marketCategory -> {
            Map<String, Object> map = new HashMap<>();
            Integer categoryId = marketCategory.getId();
            List<MarketGoods> goodsList = this.list(categoryId, 1, categoryGoodsLimit);
            map.put("goodsList", goodsList);
            map.put("id", categoryId);
            map.put("name", marketCategory.getName());
            return map;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<MarketGoods> list(Integer categoryId, int page, int categoryGoodsLimit) {
        MarketGoodsExample example = new MarketGoodsExample();
        PageHelper.startPage(page, categoryGoodsLimit);
        example.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        return goodsMapper.selectByExample(example);
    }

    @Override
    public List<MarketGoods> goodsList(boolean isHot, boolean isNew, int page, int hotLimit) {
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        if (isHot) {
            criteria.andIsHotEqualTo(true);
        }
        if (isNew) {
            criteria.andIsNewEqualTo(true);
        }
        PageHelper.startPage(1, hotLimit);
        return goodsMapper.selectByExample(example);
    }


    @Override
    public GoodsDetailData detail(Integer goodsId, int userId) {
        // 直接根据主键来做查询了，如果你做的是逻辑删除，还要添加一个条件deleted=false
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(goodsId);
        // 和goods的关系 一对多的关系
        // 查询条件都是 goods_id = ? and deleted = false order by add_time desc
        List<MarketGoodsAttribute> attribute = this.getAttributes(goodsId);
        List<MarketGoodsProduct> productList = this.getProducts(goodsId);
        List<Map> specificationList = this.getSpecifications(goodsId);

        // market_goods和brand之间的关系，market_goods表中有个brand_id字段
        Integer brandId = marketGoods.getBrandId();
        MarketBrand marketBrand = brandService.findById(brandId);

        // 封装comment：当前商品评价的数量和前两条数据
        // 传入了goodsId和评论的类型（tinyint → Byte）
        Map<String, Object> commentMap = commentService.findById(goodsId, (byte) 0, 1, 2);

        // issue → 所有的常见问题
        List<MarketIssue> issueList = issueService.list();

        // userHasCollection → 用户是否有收藏 → 用户id,商品id,收藏类型
        int userHasCollection = 0;
        if (userId != 0) {
            userHasCollection = collectService.hasCollection(goodsId, (byte) 0, userId);
        }
        
        //插入到浏览足迹中
        MarketFootprint record = new MarketFootprint();
        record.setUserId(userId);
        record.setGoodsId(goodsId);
        record.setAddTime(new Date());
        record.setUpdateTime(new Date());
        footprintMapper.insertSelective(record);
                
                
                
        GoodsDetailData data = GoodsDetailData.builder()
                .attribute(attribute)
                .productList(productList)
                .specificationList(specificationList)
                .brand(marketBrand)
                .info(marketGoods)
                .comment(commentMap)
                .issue(issueList)
                .userHasCollect(userHasCollection)
                .share(true)
                .shareImage("")
                .build();
        return data;
    }

    @Override
    public List<MarketGoodsAttribute> getAttributes(Integer goodsId) {
        MarketGoodsAttributeExample example = new MarketGoodsAttributeExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId);
        example.setOrderByClause("add_time desc");
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(example);
        return attributes;
    }

    @Override
    public List<MarketGoodsProduct> getProducts(Integer goodsId) {
        MarketGoodsProductExample example = new MarketGoodsProductExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId);
        example.setOrderByClause("add_time desc");
        List<MarketGoodsProduct> productList = productMapper.selectByExample(example);
        return productList;
    }

    @Override
    public List<Map> getSpecifications(Integer goodsId) {
        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(goodsId);
        example.setOrderByClause("add_time desc");
        List<MarketGoodsSpecification> specificationList = specificationMapper.selectByExample(example);
        Map<String, List<MarketGoodsSpecification>> collect = specificationList.stream().collect(Collectors.groupingBy(MarketGoodsSpecification::getSpecification));
        List<Map> specificationMapList = new ArrayList<>();
        for (String name : collect.keySet()) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("valueList", collect.get(name));
            specificationMapList.add(map);
        }
        return specificationMapList;
    }

    @Override
    public MarketGoods findById(Integer id) {
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andIdEqualTo(id);
        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        if (goodsList != null && goodsList.size() == 1) {
            return goodsList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public PageData queryByCategory(Integer categoryId, int page, int limit) {
        PageHelper.startPage(page, limit);
        MarketGoodsExample example = new MarketGoodsExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andCategoryIdEqualTo(categoryId);
        example.setOrderByClause("add_time");
        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        List<Map> list = new ArrayList<>();
        for (MarketGoods marketGoods : goodsList) {
            Map<String, Object> map = new HashMap<>();
            map.put("brief", marketGoods.getBrief());
            map.put("counterPrice", marketGoods.getCounterPrice());
            map.put("id", marketGoods.getId());
            map.put("isHot", marketGoods.getIsHot());
            map.put("isNew", marketGoods.getIsNew());
            map.put("name", marketGoods.getName());
            map.put("picUrl", marketGoods.getPicUrl());
            map.put("retailPrice", marketGoods.getRetailPrice());
            list.add(map);
        }
        return PageData.list(list);
    }
    
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PageData listHistory(PageParameter pageParameter, Integer categoryId, String keyword, Integer brandId) {
        List<CategoryListData> list = new ArrayList<>();
        MarketGoodsExample example = new MarketGoodsExample();
        PageHelper.startPage(1, 10);
        if (pageParameter.getOrder() != null && pageParameter.getSort() != null) {
            example.setOrderByClause(pageParameter.getSort() + " " + pageParameter.getOrder());
        }
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (categoryId != null && categoryId != 0) {
            criteria.andCategoryIdEqualTo(categoryId);
        }
        if (keyword != null && !"".equals(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        if (brandId != null && brandId != 0) {
            criteria.andBrandIdEqualTo(brandId);
        }

        // 获取当前登录的Subject
        Subject subject = SecurityUtils.getSubject();
        // 获取当前登录用户的ID
        Integer userId = (Integer) subject.getPrincipal();

        // 检查用户ID是否不为空且keyword不为空
        if (userId != null && keyword != null) {
            // 构造查询条件
            MarketSearchHistoryExample example1 = new MarketSearchHistoryExample();
            example1.createCriteria().andKeywordEqualTo(keyword).andUserIdEqualTo(userId).andDeletedEqualTo(false);

            // 检查数据库中是否已经存在该搜索关键词
            List<MarketSearchHistory> existingHistories = searchHistoryMapper.selectByExample(example1);

            // 如果不存在，插入新记录
            if (existingHistories.isEmpty()) {
                MarketSearchHistory newSearchHistory = new MarketSearchHistory();
                newSearchHistory.setUserId(userId);
                newSearchHistory.setKeyword(keyword);
                newSearchHistory.setAddTime(new Date()); // 假设有addTime字段
                newSearchHistory.setUpdateTime(new Date());
                searchHistoryMapper.insertSelective(newSearchHistory);
            } else {
                // 如果存在，只更新update_time字段
                MarketSearchHistory existingHistory = existingHistories.get(0);
                existingHistory.setUpdateTime(new Date());
                searchHistoryMapper.updateByPrimaryKeySelective(existingHistory);
            }

            // 查询用户的搜索历史记录，去重，并按update_time倒序排列
            example1 = new MarketSearchHistoryExample();
            example1.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
            example1.setOrderByClause("update_time desc");
            List<MarketSearchHistory> marketSearchHistories = searchHistoryMapper.selectByExample(example1);

            // 使用Set去除重复的关键词
            Set<String> uniqueKeywords = marketSearchHistories.stream()
                    .map(MarketSearchHistory::getKeyword)
                    .collect(Collectors.toCollection(() -> new LinkedHashSet<>()));

            // 过滤出Set中存在的搜索历史记录，保持原有的倒序
            List<MarketSearchHistory> uniqueMarketSearchHistories = marketSearchHistories.stream()
                    .filter(history -> uniqueKeywords.contains(history.getKeyword()) && uniqueKeywords.remove(history.getKeyword()))
                    .collect(Collectors.toList());

            // 此处 uniqueMarketSearchHistories 即为去重后按时间倒序排列的搜索历史列表
            // 可以将其展示给用户或进行其他处理
        }

        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        for (MarketGoods marketGoods : goodsList) {
            CategoryListData listData = new CategoryListData();
            listData.setId(marketGoods.getId());
            listData.setName(marketGoods.getName());
            listData.setBrief(marketGoods.getBrief());
            listData.setCounterPrice(marketGoods.getCounterPrice());
            listData.setIsHot(marketGoods.getIsHot());
            listData.setIsNew(marketGoods.getIsNew());
            listData.setPicUrl(marketGoods.getPicUrl());
            listData.setRetailPrice(marketGoods.getRetailPrice());
            list.add(listData);
        }
        PageData data = PageData.list(list);
        return data;
    }
}
